package com.yksj.healthtalk.ui.recharge;

import java.util.ArrayList;
import java.util.List;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import org.handmark.pulltorefresh.library.PullToRefreshListView;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.entity.ChargeRecordEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.TimeUtil;
import com.yksj.healthtalk.utils.ToastUtil;
/**
 * 充值历史
 * @author root
 *
 */
public class RechargeHistory extends BaseFragmentActivity implements OnClickListener, OnRefreshListener<ListView> {

	private TextView mDate;
	private String date = null;
	private ChargeListAdapter adapter;
	private List<ChargeRecordEntity> 	chargeMetaData = new ArrayList<ChargeRecordEntity>();
	private PullToRefreshListView refreshListView;
	private int orderId;/* 充值历史查询 排序id */
	private TextView mRecordCountText;
	private TextView rechargeAll;//充值总金额

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.charge_record_listview);
		initTitle();
		initView();
		initData();
	}

	private void initData() {
		queryChargeHistoryEntity(String.valueOf(Long.MAX_VALUE));
	}

	/**
	 * 充值历史查询 关联参数 ordId
	 * 请求历史记录
	 * 没有指定日期加载的时候date为null
	 * 第一次加载的时候oride  String.valueOf(Long.MAX_VALUE)表示最大值
	 */
	private void queryChargeHistoryEntity(final String oride){
		HttpRestClient.doHttpQueryChongZhiHostory(SmartFoxClient.getLoginUserId(), oride,date, new AsyncHttpResponseHandler(){
			private LodingFragmentDialog showLodingDialog;
			@Override
			public void onSuccess(int statusCode, String content) {
				super.onSuccess(statusCode, content);
				try {
					JSONObject jsonObject = new JSONObject(content);
					//如果相等，则代表是第一次获取数据。不相等则为下拉刷新获取数据
					if(!String.valueOf(Long.MAX_VALUE).equals(oride)) {
						refreshListView.onRefreshComplete();
						chargeMetaData.addAll(ChargeRecordEntity.parseToListRecord(jsonObject.getJSONArray("datas")));
					}else {
						//第一次数据加载时只需要取等
						chargeMetaData = ChargeRecordEntity.parseToListRecord(jsonObject.getJSONArray("datas"));
					}
					String count = jsonObject.getString("count");
					/*String recordCountStr = getResources().getString(R.string.sell_record_info,
							count+"");*/
					rechargeAll.setText("充值总额 : "+count+"元");
					mRecordCountText.setText("详细记录(共"+chargeMetaData.size()+"条)");
					adapter.notifyDataSetChanged();
					if(chargeMetaData.size()>0)
					orderId = Integer.parseInt(chargeMetaData.get(chargeMetaData.size()-1).getId());
					if(chargeMetaData.size()==0){
						ToastUtil.showToastPanl("没有记录");
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			@Override
			public void onStart() {
				showLodingDialog = LodingFragmentDialog.showLodingDialog(getSupportFragmentManager(), "马上来了");
			}
			@Override
			public void onFailure(Throwable error) {
				ToastUtil.showBasicShortToast(RechargeHistory.this, "请稍后重试...");
			}
			@Override
			public void onFinish() {
				showLodingDialog.dismissAllowingStateLoss();
			}
		});
	}

	private void initView() {
		mDate = (TextView)findViewById(R.id.recorddate);
		mDate.setOnClickListener(this);
		mDate.setText(TimeUtil.getMoneyTime().substring(0,4)+"");
		refreshListView = (PullToRefreshListView)findViewById(R.id.chargeListview);
		ListView mListView = refreshListView.getRefreshableView();
		adapter = new ChargeListAdapter(this);
		mListView.setAdapter(adapter);
		mRecordCountText = (TextView)findViewById(R.id.recordnum);
		//下拉刷新绑定
		refreshListView.setOnRefreshListener(this);
		titleLeftBtn.setOnClickListener(this);
		titleTextV.setText("充值历史");
		titleTextV.setTextColor(Color.BLACK);
		rechargeAll=(TextView)findViewById(R.id.recharge_all);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(data!=null){
		Bundle extras = data.getExtras();
		if(extras.containsKey("nothing"))return;
		String string = extras.getString("date");
		String string1 = extras.getString("year");
		mDate.setText(string1+"-"+string);
		date=string1+string;
		}else{
			date=null;
			mDate.setText(TimeUtil.getMoneyTime().substring(0,4)+"");
		}
		queryChargeHistoryEntity(String.valueOf(Long.MAX_VALUE));
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.recorddate:
			Intent intent=new Intent(this,ChoiseDateActivity.class);
			if(mDate.getText().toString().length()<5){
				intent.putExtra("date", TimeUtil.getMoneyTime());
			}else{
				intent.putExtra("date", mDate.getText().toString());
			}
			startActivityForResult(intent,0);
			overridePendingTransition(R.anim.anim_enter,R.anim.anim_exit);
			break;
		case R.id.title_back:
			finish();
			overridePendingTransition(R.anim.back_enter, R.anim.back_exit);
			break;

		}
	}
	
	public class ChargeListAdapter extends BaseAdapter {

		private LayoutInflater inflater;
		private Context context;

		public ChargeListAdapter(Context context) {
			this.context = context;
			inflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return chargeMetaData.size();
		}

		@Override
		public Object getItem(int position) {
			return chargeMetaData.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = inflater.inflate(R.layout.charge_record_item,
						null);
				holder.chargeContent1 = (TextView) convertView
						.findViewById(R.id.content1);
				holder.chargeDate = (TextView) convertView
						.findViewById(R.id.charge_date);
				holder.chargeContent2 = (TextView) convertView
						.findViewById(R.id.content2);
				holder.chargeTitle2 = (TextView) convertView
						.findViewById(R.id.title2);
				holder.chargeTitle1 = (TextView) convertView.findViewById(R.id.title1);
				holder.chargeTemp = (TextView) convertView.findViewById(R.id.charge_record_money_num);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			changeText(holder,position);
			return convertView;
		}

		public void changeText(ViewHolder holder,int viewposition) {
			String str = "";
			ChargeRecordEntity entity = chargeMetaData.get(viewposition);
			/* 常量改变 */
			holder.chargeTitle1.setText(getStringFromResource(R.string.charge_trade_num));	//交易号
			holder.chargeTitle2.setText(getStringFromResource(R.string.charge_payment));		//交易方式
			/* 从服务器获取 */
			holder.chargeContent1.setText(entity.getTransactionNum());
			holder.chargeContent2.setText(entity.getChargeWay());
			holder.chargeTemp.setText(entity.getChargeNum());
			str = getStringFromResource(R.string.charge_record_time, entity.getChargeTime());
			holder.chargeDate.setText(str);
		}

		public String getStringFromResource(int resid) {
			return context.getResources().getString(resid);
		}
		
		public String getStringFromResource(int resid,String str1) {
			return context.getResources().getString(resid,str1);
		}
		
		private class ViewHolder {
			private TextView chargeDate;//成交时间
			private TextView chargeContent1;//交易时间
			private TextView chargeContent2;//交易方式
			private TextView chargeTitle2;//标题2
			private TextView chargeTitle1;//标题1
			private TextView chargeTemp;//标题3
		}
	}
	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		queryChargeHistoryEntity(orderId+"");
	}
}
